package com.hotel.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import com.hotel.config.FileServerConfig;
import com.hotel.dao.mapper.ImageInfoMapper;
import com.hotel.entity.ImageInfo;
import com.hotel.service.ImageInfoService;
import com.hotel.utils.RandomUtil;

public class ImageInfoServiceImpl implements ImageInfoService{

	@Autowired
	private ImageInfoMapper imageInfoMapper;
	@Autowired
	private FileServerConfig fileServerConfig;

	@Override
	public String save(ImageInfo imageInfo, MultipartFile file) {
		String name = file.getOriginalFilename();
	    String suffix = name.substring(name.lastIndexOf(".")+1);
	    DateFormat format = new SimpleDateFormat("yyyymmddhhmmssSSS");
        name = format.format(new Date())+RandomUtil.getRandomRandom(15)+"."+suffix;
        String url = uploadLocal(file, name);
        //imageInfo.setSize(file.getSize());
        
        
        
        
		return url;
	}
	
	
	public String uploadLocal(MultipartFile file,String name){
		String path;
		try {
		FileOutputStream fos = null;
		InputStream is = file.getInputStream();
		byte[] buffer = new byte[1024];
		fos = new FileOutputStream(new File(fileServerConfig.getRoot()+fileServerConfig.getPath()+name));
		while ((is.read(buffer))!=-1) {
			fos.write(buffer);
		}
		fos.flush();
	    fos.close();
	    if(fileServerConfig.getPath()!=null)
 			 path = fileServerConfig.getPath().replace("\\", "/");
 		 else{
 			 throw new RuntimeException("文件服务器配置错误：资源路径不能为空");
 		 }
		}
	    catch (Exception e) {
	    	throw new RuntimeException(e.getMessage());  
		}
	    return path+name;
} 
	

	

}
